package com.situ.mall.interceptor;


import com.situ.mall.pojo.entity.Admin;
import com.situ.mall.pojo.query.AdminQuery;
import com.situ.mall.service.IAdminService;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;

public class LoginInterceptor implements HandlerInterceptor {
    private IAdminService adminService;

    public LoginInterceptor(IAdminService adminService) {
        this.adminService = adminService;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.判断用户有没有登录
        //2.如果登录了，就放行，可以正常访问后台资源
        //3.如果没有登录，跳转到登录界面
        HttpSession session = request.getSession();
        Admin admin = (Admin) session.getAttribute("admin");

        if (ObjectUtils.isEmpty(admin)) {
            Cookie[] cookies = request.getCookies();
            Cookie cookie = null;
            for (Cookie c : cookies) {
                String name = c.getName();
                if ("autoLogin".equals(name)) {
                    cookie = c;
                    break;
                }
            }
            if (!ObjectUtils.isEmpty(cookie)) {
                String[] values = cookie.getValue().split("&");
                AdminQuery adminQuery = new AdminQuery();
                adminQuery.setAccount(values[0]);
                adminQuery.setPassword(values[1]);
                Admin login = adminService.login(adminQuery.getAccount(), adminQuery.getPassword());
                if (!ObjectUtils.isEmpty(login)) {
                    session.setAttribute("admin", login);
                    return true;
                }
            }

        }
        if (admin == null) {
            //没有登录，跳转到登录界面
            response.sendRedirect("/page/login");
            return false;
        }
        //已经登录，放行
        return true;
    }
}
